package com.test.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.Queue;
import javax.jms.ConnectionFactory;

public class JMSServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	@Resource(name = "foo")
	private Topic fooTopic;

	@Resource(name = "bar")
	private Queue barQueue;

	@Resource
	private ConnectionFactory connectionFactory;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		try
		{
			Connection connection = connectionFactory.createConnection();
			connection.start();

			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			MessageProducer producer = session.createProducer(fooTopic);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

			TextMessage message = session.createTextMessage("Hello World!");

			producer.send(message);
			
//			session.commit();
			session.close();

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			MessageConsumer consumer = session.createConsumer(fooTopic);

			while (true)
			{
				Message m = consumer.receive(1);
				if (m != null)
				{
					if (m instanceof TextMessage)
					{
						message = (TextMessage) m;
						System.out.println("Reading message: " + message.getText());
					}
					else
					{
						break;
					}
				}
			}
//			session.commit();
			session.close();

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public JMSServlet()
	{
		super();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
	}

}
